export interface Params {
	param: string;
	order: string;
	// param: { [field: string]: any | [any, any]; };
	// order: { [field: string]: 1 | -1 | 0 | true | false | 'true' | 'false' | 'TRUE' | 'FALSE' | 'True' | 'False' | 'asc' | 'desc' | 'ASC' | 'DESC'; };
}

export default function p2q(p: Params) {
	if (!p.param) {
		p.param = JSON.stringify({});
	}
	if (!p.order) {
		p.order = JSON.stringify({});
	}
	const criteria = ((param) => {
		const fields = Object.keys(param);
		return fields.reduce((q, field) => {
			const v = param[field];
			if (Array.isArray(v)) { // 区间查询
				if (v[0] && v[1]) {
					q[field] = { $gte: parseInt(v[0]), $lte: parseInt(v[1]) }
				} else if (v[0] && !v[1]) {
					q[field] = { $gte: parseInt(v[0]) }
				} else if (!v[0] && v[1]) {
					q[field] = { $lte: parseInt(v[1]) }
				}
			} else if (v === '') {
				q[field] = '';	// 筛选条件选择“空”时
			} else if (v === true || v === false) {
				q[field] = v;
			} else if (typeof v === 'string') {	// 模糊查询
				q[field] = {
					$regex: '.*' + v + '.*',
					$options: "i"
				};
			} else {
				q[field] = v;
			}
			return q;
		}, {} as { [field: string]: any; });
	})(JSON.parse(p.param));
	const sort = ((order) => {
		const fields = Object.keys(order);
		return fields.reduce((q, field) => {
			const v = order[field];
			q[field] = (!v || v === 'false' || v === 'FALSE' || v === 'False' || v === 'desc') ? -1 : 1;
			return q;
		}, {} as { [field: string]: 1 | -1; });
	})(JSON.parse(p.order));
	return {
		criteria,
		sort
	};
}
